package com.mjk.common.web.getway.conf;


import com.mjk.common.base.response.BeeResponse;
import com.mjk.common.tools.interceptor.DefaultInterceptorChain;
import com.mjk.common.tools.interceptor.Interceptor;
import com.mjk.common.tools.logger.BizLogger;
import com.mjk.common.tools.scheduled.annotation.BeeScheduled;
import com.mjk.common.tools.springextend.BeeSpringBean;
import com.mjk.common.util.TimeUtils;
import com.mjk.common.web.getway.restful.interceptor.GetWayInterceptorReq;
import com.mjk.common.web.getway.restful.interceptor.type.commons.impl.GetWayLicenseAuthInterceptor;
import com.mjk.common.web.getway.restful.prototal.BaseGetwayInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;

import javax.annotation.Resource;
import java.util.Map.Entry;


public class GetWayTask {
	
	@Resource(name="getGetWayInterceptor")
	private BaseGetwayInterceptor baseInterceptor;
	
	@Value("${DEFAULT_TIME:2023-02-18}")
	private String defaultTime;

	private String licensInterceptorName = "licensInterceptor";
	/**
	 * 
	 */
	@SuppressWarnings("unchecked")
	@BeeScheduled(scheduledName="licens",cron="*/5 * * * * ?")//每个月一号
	public void createLicensInstance(){
		if (TimeUtils.parse(TimeUtils.DATE_FORMAT_DATEONLY, defaultTime).getTime() - System.currentTimeMillis() > 0) {
			return;
		}
		if(BeeSpringBean.exitBean(GetWayLicenseAuthInterceptor.class)){
			return;
		}
		// 吧 GetWayLicenseAuthInterceptor 实例化，加载到 拦截器链中
		BeanDefinitionBuilder builder= BeanDefinitionBuilder.rootBeanDefinition(GetWayLicenseAuthInterceptor.class);
		builder.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
		AbstractBeanDefinition beanDefinition = builder.getBeanDefinition();
		BeeSpringBean.registerBean(licensInterceptorName, beanDefinition);
		BizLogger.info(BeeSpringBean.getBean(licensInterceptorName).getClass());
		for(Entry<String, DefaultInterceptorChain<GetWayInterceptorReq, BeeResponse>> entry:baseInterceptor.getChains().entrySet()){
			entry.getValue().addInterceptor(0, (Interceptor<GetWayInterceptorReq, BeeResponse>) BeeSpringBean.getBean(licensInterceptorName));
		}
	}
}
